
package net.swa.dewei.service.impl;

import net.swa.dewei.beans.entity.District;
import net.swa.dewei.beans.entity.FuwuZhan;
import net.swa.dewei.beans.entity.FuwuZhanArea;
import net.swa.dewei.beans.entity.MenDian;
import net.swa.dewei.beans.vo.VoExpFuwuZhan;
import net.swa.dewei.beans.vo.ZTreeNode;
import net.swa.dewei.service.FuwuZhanService;
import net.swa.system.beans.entity.Role;
import net.swa.system.beans.entity.User;
import net.swa.system.dao.HibernateDaoSupport;
import net.swa.system.util.SysConst;
import net.swa.util.BuzConst;
import net.swa.util.DateUtils;
import net.swa.util.EncryptTool;
import net.swa.util.io.ExcelUtil;
import net.swa.util.io.enums.MsOfficeVersion;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Service;

@Service("fuwuZhanService")
public class FuwuZhanServiceImpl extends HibernateDaoSupport implements FuwuZhanService
{
    private static final Logger log = Logger.getLogger(FuwuZhanServiceImpl.class);

    @Override
    public FuwuZhan addFuwuzhanByUser(final long id)
    {
        FuwuZhan model = null;
        User u = (User) getCurrentSession().get(User.class, id);
        model = new FuwuZhan();
        model.setName(u.getRealName());
        getCurrentSession().save(model);
        u.setFuwuzhanId(model.getId());
        getCurrentSession().update(u);
        return model;

    }

    @Override
    public FuwuZhan process(final long id , final Long fid)
    {
        FuwuZhan model = null;
        if (null != fid)
        {
            model = (FuwuZhan) getCurrentSession().get(FuwuZhan.class, fid);
        }
        else
        {
            User u = (User) getCurrentSession().get(User.class, id);
            model = new FuwuZhan();
            model.setName(u.getRealName());
            getCurrentSession().save(model);
            u.setFuwuzhanId(model.getId());
            getCurrentSession().update(u);
        }
        return model;
    }

    @Override
    public boolean saveModel(final FuwuZhan model)
    {
        EncryptTool tool;
        try
        {
            getCurrentSession().save(model);
            User u = new User();
            u.setUserid(model.getLoginName());
            u.setFuwuzhanId(model.getId());
            tool = new EncryptTool(u.getUserid());
            u.setPassword(tool.encrypt("888888"));
            u.setUserType(SysConst.USER_TYPE_FUWUZHAN);
            u.setRegDate(DateUtils.getCurrDate(null));
            u.setRealName(model.getName());// 服务站名称
            u.setFuwuzhanId(model.getId());
            // 将服务站角色分配
            Query q = getCurrentSession().createQuery("from Role where name =:name");
            q.setString("name", BuzConst.ROLE_FUWUZHAN);
            @SuppressWarnings("unchecked")
            List<Role> list = q.list();
            if (null != list && list.size() > 0)
            {
                u.setRole(list.get(0));
            }
            getCurrentSession().save(u);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @SuppressWarnings("unchecked")
    @Override
    public boolean delete(final Long[] ids)
    {

        if (null != ids && ids.length > 0)
        {
            Query q = getCurrentSession().createQuery("delete from User where userid=:userid");
            for (Long id : ids)
            {
                FuwuZhan m = (FuwuZhan) getCurrentSession().get(FuwuZhan.class, id);
                if (null != m)
                {
                    String loginName = m.getLoginName();
                    q.setString("userid", loginName);
                    q.executeUpdate();
                    getCurrentSession().delete(m);
                    log.debug("执行删除服务站操作,物理删除 userid is " + loginName + " ,服务站是：" + m);
                }

                q = getCurrentSession().createQuery("from MenDian where fuwuzhanId=:id");
                q.setLong("id", id);
                List<MenDian> ml = q.list();
                if (null != ml && ml.size() > 0)
                {
                    //                    q = getCurrentSession().createQuery("UPDATE WeixinInfo set mendian=0 where openid=:wxid");
                    for (MenDian md : ml)
                    {
                        //                        if (!StringUtils.isBlank(md.getWxid()))
                        //                        {
                        //                            q.setString("wxid", md.getWxid());
                        //                            q.executeUpdate();
                        //                        }
                        md.setFuwuzhanId(null);
                        getCurrentSession().update(md);
                        //                        getCurrentSession().delete(md);
                    }
                }
            }
        }
        return true;
    }

    @Override
    public boolean batchUpdate(final Long[] ids , final String password)
    {
        if (null != ids && ids.length > 0)
        {
            Query q = getCurrentSession().createQuery("update  User set password=:password  where userid=:userid");
            try
            {
                for (Long id : ids)
                {
                    if (null != id)
                    {
                        FuwuZhan f = (FuwuZhan) getCurrentSession().get(FuwuZhan.class, id);
                        if (!StringUtils.isBlank(f.getLoginName()))
                        {
                            EncryptTool tool = new EncryptTool(f.getLoginName());
                            String pwd = tool.encrypt(password);
                            q.setString("userid", f.getLoginName());
                            q.setString("password", pwd);
                            q.executeUpdate();
                        }
                        else
                        {
                            return false;
                        }

                    }
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        return true;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<ZTreeNode> queryTreeNodesJson(Long id)
    {
        List<ZTreeNode> result = new ArrayList<ZTreeNode>();
        Session session = getCurrentSession();
        Query query = null;
        HashMap<String, String> map = new HashMap<String, String>();
        if (null != id)
        {
            query = session.createQuery(" from FuwuZhanArea where fuwuzhanId=:id");
            query.setLong("id", id);
            List<FuwuZhanArea> list = query.list();
            if (null != list)
            {
                for (FuwuZhanArea a : list)
                {
                    map.put(a.getCode(), a.getTown());
                }
            }
        }
        query = session.createQuery(" from District ");
        List<District> list = query.list();

        //将选中的赋值到Tree中
        for (District def : list)
        {
            ZTreeNode treeNode = new ZTreeNode();
            treeNode.setId(def.getId());
            treeNode.setName(def.getName().toString());
            treeNode.setpId(def.getPid());

            if (3 == def.getLevel())
            {
                treeNode.setNocheck(false);
                //如果通知已经有该角色，给该角色节点打上勾
                if (map.containsKey(def.getId()))
                {
                    treeNode.setChecked(true);
                }
            }
            else
            {
                treeNode.setNocheck(false);
            }
            result.add(treeNode);
        }
        return result;
    }

    @Override
    public boolean saveModelExt(FuwuZhan model , String areas , String codes)
    {
        EncryptTool tool;
        try
        {
            Session session = getCurrentSession();
            model.setCrateDate(DateUtils.getCurrDate(null));
            session.save(model);
            User u = new User();
            u.setUserid(model.getLoginName());
            u.setFuwuzhanId(model.getId());
            tool = new EncryptTool(u.getUserid());
            u.setPassword(tool.encrypt("888888"));
            u.setUserType(SysConst.USER_TYPE_FUWUZHAN);
            u.setRegDate(DateUtils.getCurrDate(null));
            u.setRealName(model.getName());// 服务站名称
            u.setFuwuzhanId(model.getId());
            // 将服务站角色分配
            Query q = session.createQuery("from Role where name =:name");
            q.setString("name", BuzConst.ROLE_FUWUZHAN);
            @SuppressWarnings("unchecked")
            List<Role> list = q.list();
            if (null != list && list.size() > 0)
            {
                u.setRole(list.get(0));
            }
            session.save(u);
            if (!StringUtils.isBlank(areas))
            {
                Long id = model.getId();
                if (null != id)
                {
                    String[] s = areas.split(",");
                    String[] s2 = codes.split(",");
                    for (int j = 0; j < s.length; j++)
                    {
                        if (!StringUtils.isBlank(s[j]))
                        {
                            FuwuZhanArea fa = new FuwuZhanArea();
                            fa.setFuwuzhanId(id);
                            fa.setTown(s[j]);
                            if (!StringUtils.isBlank(s2[j]))
                            {
                                String code = s2[j];
                                fa.setCode(code);
                                int e = code.lastIndexOf("_");
                                if (e > 1)
                                {
                                    String pcode = code.substring(0, e);
                                    q = session.createQuery("from District where id =:id");
                                    q.setString("id", pcode);
                                    District d = (District) q.uniqueResult();
                                    if (null != d)
                                    {
                                        fa.setCity(d.getName());
                                        fa.setProvince(d.getPname());
                                    }
                                }
                            }
                            session.save(fa);
                           
                        }
                    }
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public boolean updateModelExt(FuwuZhan model , String areas , String codes)
    {
        try
        {
            Session session = getCurrentSession();
            model.setUpdateDate(DateUtils.getCurrDate(null));
            session.update(model);

            Long id = model.getId();
            Query query = session.createQuery("delete from FuwuZhanArea where fuwuzhanId=:id ");
            query.setLong("id", id);
            query.executeUpdate();
            if (!StringUtils.isBlank(areas))
            {
                if (null != id)
                {
                    String[] s = areas.split(",");
                    String[] s2 = codes.split(",");
                    for (int j = 0; j < s.length; j++)
                    {
                        if (!StringUtils.isBlank(s[j]))
                        {
                            FuwuZhanArea fa = new FuwuZhanArea();
                            fa.setFuwuzhanId(id);
                            fa.setTown(s[j]);
                            if (!StringUtils.isBlank(s2[j]))
                            {
                                String code = s2[j];
                                fa.setCode(code);
                                int e = code.lastIndexOf("_");
                                if (e > 1)
                                {
                                    String pcode = code.substring(0, e);
                                    query = session.createQuery("from District where id =:id");
                                    query.setString("id", pcode);
                                    District d = (District) query.uniqueResult();
                                    if (null != d)
                                    {
                                        fa.setCity(d.getName());
                                        fa.setProvince(d.getPname());
                                    }
                                }
                            }
                            session.save(fa);
                        }
                    }
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public boolean updateJiebang(Long[] ids)
    {
        if (null != ids && ids.length > 0)
        {
            for (Long id : ids)
            {
                FuwuZhan m = (FuwuZhan) getCurrentSession().get(FuwuZhan.class, id);
                m.setMac(null);
                getCurrentSession().update(m);
            }
        }
        return true;
    }

    @SuppressWarnings("unchecked")
    @Override
    public HSSFWorkbook exportExcel(String name , String province , String city , String town)
    {
        if (log.isDebugEnabled())
        {
            log.debug("传入参数 province is" + province + " ,city is " + city + ",town:" + town);
        }
        StringBuilder sql = new StringBuilder();
        Query query = null;
        sql.append(" from FuwuZhan   where 1=1 ");

        if (!StringUtils.isBlank(name))
        {
            sql.append(" and name  like :name");
        }
        if (null != province)
        {
            sql.append(" and province like :province ");
        }
        if (!StringUtils.isBlank(city))
        {
            sql.append(" and city  like :city");
        }
        if (!StringUtils.isBlank(town))
        {
            sql.append(" and town like :town");
        }

        query = getCurrentSession().createQuery(sql.toString());

        if (!StringUtils.isBlank(name))
        {
            query.setString("nickname", "%" + name + "%");
        }
        if (null != province)
        {
            query.setString("nickname", province + "%");
        }
        if (!StringUtils.isBlank(city))
        {
            query.setString("nickname", city + "%");
        }
        if (!StringUtils.isBlank(town))
        {
            query.setString("nickname", town + "%");
        }

        query.setMaxResults(BuzConst.MAX_RESULT);
        List<FuwuZhan> list = query.list();
        HSSFWorkbook book = null;
        if (null != list && list.size() > 0)
        {
            // 要从对象中获取的属性名
            String fieldNames[] = { "id", "name", "loginName", "province", "city", "town", "address", "lxr", "lxrTel", "detailInfo", "crateDate", "updateDate" };
            String titleNames[] = { "序号", "服务站名称", "登陆名称", "省", "市", "县", "地址", "联系人", "联系电话", "说明", "创建时间", "更新时间" };

            try
            {
                book = ExcelUtil.writeToExcelFile(list, fieldNames, titleNames, 0, 0, "filename", "sheetname", true, null, MsOfficeVersion.Office2003, null);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        return book;
    }

    @SuppressWarnings("unchecked")
    @Override
    public Map<String, Object> addExcel(String filePath , String errFilePath)
    {
        Map<String, Object> map = new HashMap<String, Object>();
        String[][] data = new String[8][];
        try
        {
            data = ExcelUtil.readFromExcelFile(filePath, 1, 0, 8, "yyyy-MM-dd", "");
            if (null != data && data.length > BuzConst.MAX_RESULT)
            {
                map.put("success", false);
                map.put("message", "最多一次导入" + BuzConst.MAX_RESULT + "条记录");
                return map;
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            log.debug("服务站信息出现异常");
            map.put("success", false);
            map.put("message", "导入出现异常");
            return map;
        }
        map.put("success", false);
        map.put("message", "默认无数据导入失败");
        List<VoExpFuwuZhan> errlist = new ArrayList<VoExpFuwuZhan>();
        if (data.length > 1)
        {
            String[] tem = data[0];
            if (tem.length < 8)
            {
                map.put("message", "请下载模板，按照模板填写要要导入内容");
                return map;
            }
            String name = tem[0];
            String loginName = tem[1];
            String province = tem[2];
            String city = tem[3];
            String town = tem[4];
            String address = tem[5];
            String lxr = tem[6];
            String lxrTel = tem[7];

            if (StringUtils.isBlank(name) || StringUtils.isBlank(loginName) || StringUtils.isBlank(province) || StringUtils.isBlank(city) || StringUtils.isBlank(town) || StringUtils.isBlank(address) || StringUtils.isBlank(lxr) || StringUtils.isBlank(lxrTel))
            {
                map.put("message", "请按照模板填写要要导入内容");
                return map;
            }
            else if ((province.contains("省")) && (city.contains("市")) && (town.contains("县")) && (name.contains("服务站名称")) && (loginName.contains("登陆名称")) && (address.contains("地址")) && (lxr.contains("联系人")) && (lxrTel.contains("电话")))
            {
                Session session = getCurrentSession();
                Query query = null;

                String fwzCheckHql = "from FuwuZhan where loginName=:loginName";
                Role r = null;
                Query q = session.createQuery("from Role where name =:name");
                q.setString("name", BuzConst.ROLE_FUWUZHAN);
                List<Role> list = q.list();
                if (null != list && list.size() > 0)
                {
                    r = list.get(0);
                }
                for (int i = 1; i < data.length && i <= BuzConst.MAX_RESULT; i++)//最大支持Const.MAX_RESULT个批量导入
                {
                    tem = data[i];
                    name = tem[0];
                    loginName = tem[1];
                    province = tem[2];
                    city = tem[3];
                    town = tem[4];
                    address = tem[5];
                    lxr = tem[6];
                    lxrTel = tem[7];

                    VoExpFuwuZhan p = new VoExpFuwuZhan();
                    p.setName(name);
                    p.setLoginName(loginName);
                    p.setProvince(province);
                    p.setCity(city);
                    p.setTown(town);
                    p.setAddress(address);
                    p.setLxr(lxr);
                    p.setLxrTel(lxrTel);

                    if (StringUtils.isBlank(province) && StringUtils.isBlank(city) && StringUtils.isBlank(town) && StringUtils.isBlank(name) && StringUtils.isBlank(loginName) && StringUtils.isBlank(address) && StringUtils.isBlank(lxr) && StringUtils.isBlank(lxrTel))
                    {
                        //第一步校验非空
                        break;
                    }

                    if (StringUtils.isBlank(name) || StringUtils.isBlank(loginName))
                    {
                        //第一步校验非空
                        p.setErrorMsg("必填数据不可以有空,请检查");
                        errlist.add(p);
                        continue;
                    }

                    //第2步校验价格合法
                    Pattern pattern1 = Pattern.compile("^\\w+$");
                    Matcher matcher1 = pattern1.matcher(loginName);
                    if (!matcher1.matches())
                    {
                        p.setErrorMsg("登录名格式不合法，英文");
                        errlist.add(p);
                        continue;
                    }

                    query = session.createQuery(fwzCheckHql);
                    query.setString("loginName", loginName);

                    List c1 = query.list();
                    if (null == c1 || 0 == c1.size())
                    {
                        FuwuZhan f = new FuwuZhan();
                        f.setName(name);
                        f.setLoginName(loginName);
                        f.setProvince(province);
                        f.setCity(city);
                        f.setTown(town);
                        f.setAddress(address);
                        f.setLxr(lxr);
                        f.setLxrTel(lxrTel);
                        EncryptTool tool;
                        try
                        {
                            f.setCrateDate(DateUtils.getCurrDate(null));
                            session.save(f);
                            User u = new User();
                            u.setUserid(loginName);
                            u.setFuwuzhanId(f.getId());
                            tool = new EncryptTool(u.getUserid());
                            u.setPassword(tool.encrypt("888888"));
                            u.setUserType(SysConst.USER_TYPE_FUWUZHAN);
                            u.setRegDate(DateUtils.getCurrDate(null));
                            u.setRealName(f.getName());// 服务站名称
                            u.setFuwuzhanId(f.getId());
                            // 将服务站角色分配
                            if (null != r)
                            {
                                u.setRole(r);
                            }
                            session.save(u);
                        }
                        catch (Exception e)
                        {
                            e.printStackTrace();
                            log.debug("ERROR:导入服务站信息出错in EncryptTool" + e);
                        }
                        continue;
                    }
                    else
                    {
                        p.setErrorMsg("本网已经存在该服务站登录名");
                        errlist.add(p);
                        continue;
                    }
                }
                map.put("success", true);
                map.put("message", "导入成功");
                if (errlist.size() > 0)
                {
                    map.put("message", "有数据不合法");

                    String fieldNames[] = {"name", "loginName", "province", "city", "town", "address", "lxr", "lxrTel", "errorMsg" };
                    String titleNames[] = {"服务站名称", "登陆名称", "省", "市", "县", "地址", "联系人", "联系电话", "错误信息" };
                    try
                    {
                        String fileName = System.currentTimeMillis() + "";
                        fileName = ExcelUtil.writeToExcelFileTemp(errlist, fieldNames, titleNames, 0, 0, errFilePath + "\\" + fileName, "sheetname", true, null, MsOfficeVersion.Office2003, null);
                        map.put("errorFile", fileName);
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
            }
            else
            {
                map.put("success", false);
                map.put("message", "请下载模板，按照模板填写要要导入内容");
                return map;
            }
        }
        else
        {
            map.put("success", false);
            map.put("message", "无数据导入,请按模板填写导入");
        }
        return map;
    }
}